package cn.zzuli.loginandregister;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {
    private long exitTime = 0;
    private Button login;
    private Button register;
    String loginUrl ="https://www.wanandroid.com/user/login";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_main );

        EditText etName = findViewById ( R.id.username );
        EditText etPwd = findViewById ( R.id.userpwd );

        login = (Button) findViewById(R.id.login_btn);
        register = (Button) findViewById(R.id.register_btn);

        login.setOnClickListener ( new View.OnClickListener (){
            @Override
            public void onClick(View v) {
                String name = etName.getText().toString ();
                String pwd = etPwd.getText().toString ();
                new Thread(){
                    @Override
                    public void run(){
                        String data1 = LOGIN ( name,pwd );
                        try {
                            JSONObject object = new JSONObject (data1);
                            int errorCode = object.optInt ( "errorCode" );
                            String errorMsg = object.optString ( "errorMsg" );
                            //System.out.println (errorCode+"  "+errorMsg);
                            if(errorCode == 0){
                                //登陆成功，跳转至主页面
                                //Activity间的跳转使用Intent，构造函数两个参数，1：当前上下文Context，一般使用:类名.this,
                                Intent intent = new Intent(MainActivity.this,LoginActivity.class);//2.要跳转到的Activity
                                intent.putExtra("link","https://www.wanandroid.com/");//如需携带参数，使用intent.putExtra方法添加参数
                                startActivity(intent);//执行跳转
                            }else{
                                //失败，显示错误信息
                                runOnUiThread ( new Runnable () {
                                    @Override
                                    public void run() {
                                        Toast.makeText ( MainActivity.this,errorMsg,
                                                Toast.LENGTH_SHORT ).show ();
                                    }
                                } );

                            }
                        } catch (JSONException e) {
                            e.printStackTrace ();
                        }
                    }
                }.start();
            }
        } );

        register.setOnClickListener(new View.OnClickListener (){
            public void onClick(View v){
                //setContentView ( R.layout.activity_register );
                Intent intent = new Intent(MainActivity.this,RegisterActivity.class);
                startActivity(intent);//执行跳转
            }
        });
    }
    private String LOGIN(String name, String pwd) {
        try {
            URL url = new URL(loginUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //conn.setReadTimeout(5000);
            //conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            //conn.setDoInput(true);
            conn.setUseCaches(false);
            String str = "username=" + URLEncoder.encode(name, "utf-8")
                    + "&password=" + URLEncoder.encode(pwd, "utf-8");
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(str.getBytes());
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                String s = stream2String ( inputStream );
                //System.out.println(s);
                return s;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String stream2String(InputStream is){
        BufferedReader br=new BufferedReader(new InputStreamReader (is));
        StringBuffer buffer=new StringBuffer();
        String line=null;
        try{
            while ((line=br.readLine()) != null){
                buffer.append(line);
            }
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace ();
        }
        return null;
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 3000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    //按两次“返回”退出Activity，按下第一次时，使用Toast提示“再按一次退出！”

    /*public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 3000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }*/

}